package com.wumao.service;

import com.wumao.NotFoundException;
import com.wumao.mapper.TypeMapper;
import com.wumao.pojo.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gaowumao
 * @Decripted
 * @Email none-j@qq.com
 * @create 2021-04-15 20:12
 */
@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeMapper typeMapper;
    /*增删改需要提交事务*/
    @Transactional
    @Override
    public Type addType(Type type) {
        return typeMapper.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeMapper.findById(id).get();
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeMapper.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeMapper.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
      Sort  sort = null;
        sort= Sort.by(Sort.Direction.DESC,"blogs.size");
      Pageable pageable = null;
        pageable =  PageRequest.of(0,size,sort);
        return typeMapper.findTop(pageable);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeMapper.deleteById(id);
    }

    @Override
    public Type getTypeByname(String name) {
        return typeMapper.queryByName(name);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeMapper.findById(id).get();
        if (t==null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,t);
        return typeMapper.save(t);
    }
}
